<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- 1. 搜索区域 输入框 -->
    <van-search
      v-model.trim="keyword"
      show-action
      placeholder="请输入搜索关键词"
      @input="debounce"
    >
      <div slot="action" @click="hAddHistory(null, true)" >搜索</div>
    </van-search>

    <!-- 2. 搜索建议 -->
    <van-cell-group v-if="suggestionList.length">
      <van-cell
        icon="search"
        v-for="(item, index) in cSuggestList"
        :key="index"
        @click="hAddHistory(index)"
      >
        <div slot="title" v-html="item" @click="$router.push('/search/result?keyword=' + suggestionList[index])"></div>
      </van-cell>
    </van-cell-group>

    <!-- 3. 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录" />
      <van-cell
        v-for="(item, index) in history"
        :key="index"
      >
      <div slot="title" @click="$router.push('/search/result?keyword=' + item)">{{item}}</div>
        <van-icon name="close" @click="hDelHistory(index, false)"></van-icon>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search.js'
import { setItem, getItem } from '@/utils/history.js'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '',
      suggestionList: [], // 关键字联想
      history: getItem() || [] // 历史记录
    }
  },
  computed: {
    cSuggestList () {
      const reg = new RegExp(this.keyword, 'gi') // 声明规则:全局匹配关键字并忽略大小写
      // ↓ 根据正则：替换每一个和关键字吻合的字符串，替换为标签。
      return this.suggestionList.map((item) =>
        item.replace(reg, (val) => `<span style="color:red">${val}</span>`)
      )
    }
  },
  methods: {
    async hSearch (q) {
      this.keyword = q
      try {
        const { data } = await getSuggestion({ q })
        this.suggestionList = data.options
      } catch (err) {
        console.log(err, '获取联想词错误')
      }
    },
    hAddHistory (index, isBtn) { // 添加历史记录
      const hisList = this.history
      if (this.keyword === '') return// 如果关键字为空直接返回
      if (isBtn) { // 判断是否为搜索按钮触发
        hisList.unshift(this.keyword)// ----------------------------- 1.将当前关键字加到历史搜索数组的最前边
        const data = [...new Set(hisList)] // ----------------------- 2.历史记录数组去重
        setItem(data)// --------------------------------------------- 3.将最新历史几率保存在本地
        this.$router.push('/search/result?keyword=' + this.keyword)// 4.路由跳转到搜索结果并传参
      } else { // 非按钮直接触发(联想词触发)
        hisList.unshift(this.suggestionList[index])// 1.根据联想提示词对应的数组下标添加到历史搜索数组
        const data = [...new Set(hisList)] // ------- 2.历史记录数组去重
        setItem(data)// ----------------------------- 3.更新到本地存储
      }
    },
    hDelHistory (index) {
      this.history.splice(index, 1)
      setItem(this.history)
    },
    debounce (q) {
      if (!q) this.suggestionList = []// 如果关键字为空,清空联想字提示数组
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
      this.timer = setTimeout(() => {
        this.hSearch(q)
      }, 400)
    }
  }
}
</script>
<style lang="less" scoped>

</style>
